package cn.yunyichina.provider.sb.service.impl;

import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.hisiface.shangbao.SBMZDiagnosisInfoVo;
import cn.yunyichina.provider.iface.entity.hisiface.shangbao.SBMZDiagnosisInfoVoResponse;
import cn.yunyichina.provider.sb.constant.Constant;
import cn.yunyichina.provider.sb.dao.MedicalOutpatientDiagnosisDao;
import cn.yunyichina.provider.sb.dao.MedicalPatientDao;
import cn.yunyichina.provider.sb.entity.MedicalOutpatientDiagnosis;
import cn.yunyichina.provider.sb.entity.MedicalPatient;
import cn.yunyichina.provider.sb.util.Util;
import cn.yunyichina.provider.sb.vo.MedicalOutpatientDiagnosisVo;
import cn.yunyichina.provider.sb.vo.SbRequest;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alipay.api.response.AlipayCommerceDataSendResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

/**
 * Created by 15-AK on 2017/7/21.
 */
public class MedicalDiagnosisServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(MedicalDiagnosisServiceImpl.class);
    private MedicalPatientDao medicalPatientDao = SpringContextHandler.getBean("medicalPatientDao");
    private MedicalOutpatientDiagnosisDao medicalOutpatientDiagnosisDao = SpringContextHandler.getBean("medicalOutpatientDiagnosisDao");
    private final static String HOSPITAL_CODE = "szszyy";

    /**
     * 下载商保门诊诊断信息
     * @return
     */
    public ResponseObject getMedicalDiagnosisInfo() {
        ResponseObject responseObject = new ResponseObject();
        try {
            //查询没有从his获取门诊诊断信息的 商保患者信息及case_no 病案号不为空
            List<MedicalPatient> medicalPatientList = medicalPatientDao.selectNotDownLoadMedicalDiagnosisInfo(HOSPITAL_CODE);
            if (CollectionUtils.isNotEmpty(medicalPatientList)) {
                int current_no = 1;
                logger.info("待获取商保门诊诊疗信息的患者total_num={}", medicalPatientList.size());
                for (MedicalPatient medicalPatient : medicalPatientList) {
                    SBMZDiagnosisInfoVo mzDiagnosisInfoVo = new SBMZDiagnosisInfoVo();
                    mzDiagnosisInfoVo.setHospitalCode(medicalPatient.getOrgCode());
                    mzDiagnosisInfoVo.setMzFeeId(medicalPatient.getMzFeeId());
                    logger.info("mzFeeId={},获取商保门诊诊疗信息his入参mzDiagnosisInfoVo ={}", new Object[]{medicalPatient.getMzFeeId(),JsonUtils.toJsonString(mzDiagnosisInfoVo)});
                    ResCommon<SBMZDiagnosisInfoVoResponse> hisfiaceMzDiagnosisResponse = HisifaceService.getHisifaceClient().getSBMZDiagnosisInfo(mzDiagnosisInfoVo);
                    logger.info("mzFeeId={},获取商保门诊诊疗信息his出参hisfiaceMzDiagnosisResponse ={}", new Object[]{medicalPatient.getMzFeeId(),JsonUtils.toJsonString(hisfiaceMzDiagnosisResponse)});
                    SBMZDiagnosisInfoVoResponse sBMZDiagnosisInfoVoResponse = hisfiaceMzDiagnosisResponse.getResult();

                    if (!"0".equals(hisfiaceMzDiagnosisResponse.getResultCode())) {
                        medicalPatient.setDownLoadDiagnosisTimes(medicalPatient.getDownLoadDiagnosisTimes() + 1);
                        medicalPatient.setDownLoadDiagnosisExceptionMessage(hisfiaceMzDiagnosisResponse.getResultMessage());
                        medicalPatientDao.update(medicalPatient);
                        continue;
                    }

                    if (sBMZDiagnosisInfoVoResponse != null) {
                        logger.info("mzFeeId={},获取商保门诊诊疗信息入库",medicalPatient.getMzFeeId());
                        MedicalOutpatientDiagnosis medicalOutpatientDiagnosis = buildMedicalOutpatientDiagnosis(sBMZDiagnosisInfoVoResponse);
                        medicalOutpatientDiagnosis.setCaseNo(medicalPatient.getCaseNo());
                        medicalOutpatientDiagnosis.setMedicalPatientId(medicalPatient.getId());
                        medicalOutpatientDiagnosis.setCurrentOffset(1);
                        medicalOutpatientDiagnosis.setTotalRows(1);
                        medicalOutpatientDiagnosisDao.insert(medicalOutpatientDiagnosis);
                        //更新该患者诊断信息为已经向his拉取过了
                        medicalPatient.setDownLoadDiagnosisTimes(medicalPatient.getDownLoadDiagnosisTimes() + 1);
                        medicalPatient.setDownLoadDiagnosisFlag(new Short("1"));
                        medicalPatientDao.update(medicalPatient);
                    }
                }
            } else {
                logger.info("本次需要获取商保门诊诊疗信息的患者总条数为0");
            }
        } catch (Exception e) {
            logger.info("获取商保门诊诊疗信息异常", e);
            responseObject.setResultCodeAndMessage("-1", "获取商保门诊诊疗信息异常");
            return responseObject;
        }
        return responseObject;
    }

    /**
     * 上传商保门诊诊断信息
     */
    public void executeUploadMedicalOutpatientDiagnosis() {
        try {
            List<MedicalOutpatientDiagnosis> unuploadMedicalOutpatientDiagnosisList = medicalOutpatientDiagnosisDao.selectUnuploadMedicalOutpatientDiagnosis(HOSPITAL_CODE);
            if (CollectionUtils.isNotEmpty(unuploadMedicalOutpatientDiagnosisList)) {
                for (MedicalOutpatientDiagnosis unuploadMedicalOutpatientDiagnosis : unuploadMedicalOutpatientDiagnosisList) {
                    logger.info("mzFeeId={},待上获取商保门诊诊疗信息 unuploadMedicalOutpatientDiagnosis ={}", new Object[]{unuploadMedicalOutpatientDiagnosis.getMzFeeId(),JsonUtils.toJsonString(unuploadMedicalOutpatientDiagnosis)});
                    MedicalOutpatientDiagnosisVo medicalOutpatientDiagnosisVo = new MedicalOutpatientDiagnosisVo();
                    String encryptData = Util.encryptMedicalOutpatientDiagnosis(medicalOutpatientDiagnosisVo.buildMedicalOutpatientDiagnosisVo(unuploadMedicalOutpatientDiagnosis), Constant.ENCRYPT_KEY);
                    SbRequest sbRequest = new SbRequest();
                    sbRequest.setSceneCode(Constant.MEDICAL_OUTPATIENT_DIAGNOSIS);
                    sbRequest.setEncryptData(encryptData);
                    try {
                        AlipayCommerceDataSendResponse response = Util.executeUploadMessage(sbRequest);
                        logger.info("mzFeeId={},商保门诊诊疗信息上传支付宝响应参数response ={}", new Object[]{unuploadMedicalOutpatientDiagnosis.getMzFeeId(),JsonUtils.toJsonString(response)});
                        if (response.isSuccess()) {
                            logger.info("mzFeeId={},商保门诊诊疗信息上传成功",unuploadMedicalOutpatientDiagnosis.getMzFeeId());
                            unuploadMedicalOutpatientDiagnosis.setUploadFlag(new Short("1"));
                            unuploadMedicalOutpatientDiagnosis.setUploadTimes(unuploadMedicalOutpatientDiagnosis.getUploadTimes() + 1);
                        } else {
                            logger.info("mzFeeId={},商保门诊诊疗信息上传失败",unuploadMedicalOutpatientDiagnosis.getMzFeeId());
                            unuploadMedicalOutpatientDiagnosis.setUploadTimes(unuploadMedicalOutpatientDiagnosis.getUploadTimes() + 1);
                            unuploadMedicalOutpatientDiagnosis.setExceptionMessage(response.getSubMsg());
                        }
                        medicalOutpatientDiagnosisDao.update(unuploadMedicalOutpatientDiagnosis);
                    } catch (Exception e) {
                        logger.error("商保门诊诊疗信息上传系统异常", e);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("商保门诊诊疗信息上传系统异常", e);
        }
    }

    private MedicalOutpatientDiagnosis buildMedicalOutpatientDiagnosis(SBMZDiagnosisInfoVoResponse sBMZDiagnosisInfoVoResponse) {
        MedicalOutpatientDiagnosis medicalOutpatientDiagnosis = new MedicalOutpatientDiagnosis();
        medicalOutpatientDiagnosis.setId(PKGenerator.generateId());
        medicalOutpatientDiagnosis.setOrgCode(HOSPITAL_CODE);
        medicalOutpatientDiagnosis.setMzFeeId(sBMZDiagnosisInfoVoResponse.getMzFeeId());
        medicalOutpatientDiagnosis.setPatId(sBMZDiagnosisInfoVoResponse.getPatId());
        medicalOutpatientDiagnosis.setMedicalType(Short.valueOf(sBMZDiagnosisInfoVoResponse.getMedicalType()));
        medicalOutpatientDiagnosis.setPatChargeType(Short.valueOf(sBMZDiagnosisInfoVoResponse.getPatChargeType()));
        medicalOutpatientDiagnosis.setRegTime(sBMZDiagnosisInfoVoResponse.getRegTime());
        medicalOutpatientDiagnosis.setVisitTime(sBMZDiagnosisInfoVoResponse.getVisitTime());
        medicalOutpatientDiagnosis.setHospitalCode(sBMZDiagnosisInfoVoResponse.getHospitalCode());
        medicalOutpatientDiagnosis.setHospitalName(sBMZDiagnosisInfoVoResponse.getHospitalName());
        medicalOutpatientDiagnosis.setHospitalLevel(sBMZDiagnosisInfoVoResponse.getHospitalLevel());
        medicalOutpatientDiagnosis.setHospitalType(Short.valueOf(sBMZDiagnosisInfoVoResponse.getHospitalType()));
        medicalOutpatientDiagnosis.setVisitDeptCode(sBMZDiagnosisInfoVoResponse.getVisitDeptCode());
        medicalOutpatientDiagnosis.setVisitDeptName(sBMZDiagnosisInfoVoResponse.getVisitDeptName());
        medicalOutpatientDiagnosis.setDiseaseName(sBMZDiagnosisInfoVoResponse.getDiseaseName());
        medicalOutpatientDiagnosis.setDiseaseCode(sBMZDiagnosisInfoVoResponse.getDiseaseCode());
        medicalOutpatientDiagnosis.setMedicalHistoryStatement(sBMZDiagnosisInfoVoResponse.getMedicalHistoryStatement());
        medicalOutpatientDiagnosis.setChiefComplaint(sBMZDiagnosisInfoVoResponse.getChiefComplaint());
        medicalOutpatientDiagnosis.setHistoryPresentIllness(sBMZDiagnosisInfoVoResponse.getHistoryPresentIllness());
        medicalOutpatientDiagnosis.setPastHistory(sBMZDiagnosisInfoVoResponse.getPastHistory());
        medicalOutpatientDiagnosis.setMaritalHistory(sBMZDiagnosisInfoVoResponse.getMaritalHistory());
        medicalOutpatientDiagnosis.setPersonalHistory(sBMZDiagnosisInfoVoResponse.getPersonalHistory());
        medicalOutpatientDiagnosis.setFamilyHistory(sBMZDiagnosisInfoVoResponse.getFamilyHistory());
        medicalOutpatientDiagnosis.setAllergyHistory(sBMZDiagnosisInfoVoResponse.getAllergyHistory());
        medicalOutpatientDiagnosis.setMenstruationHistory(sBMZDiagnosisInfoVoResponse.getMenstruationHistory());
        medicalOutpatientDiagnosis.setPhysicalExaminatio(sBMZDiagnosisInfoVoResponse.getPhysicalExamination());
        medicalOutpatientDiagnosis.setSpecialistExamination(sBMZDiagnosisInfoVoResponse.getSpecialistExamination());
        medicalOutpatientDiagnosis.setAuxiliaryExamination(sBMZDiagnosisInfoVoResponse.getAuxiliaryExamination());
        medicalOutpatientDiagnosis.setTreatreCommend(sBMZDiagnosisInfoVoResponse.getTreatRecommend());
        medicalOutpatientDiagnosis.setEmergencyObservationRecord(sBMZDiagnosisInfoVoResponse.getEmergencyObservationRecord());
        medicalOutpatientDiagnosis.setEmergencyRecord(sBMZDiagnosisInfoVoResponse.getEmergencyRecord());
        medicalOutpatientDiagnosis.setElectronicMedicalRecords(sBMZDiagnosisInfoVoResponse.getElectronicMedicalRecords());
        medicalOutpatientDiagnosis.setDiagnosisDoctorCode(sBMZDiagnosisInfoVoResponse.getDiagnosisDoctorCode());
        medicalOutpatientDiagnosis.setDiagnosisDoctorName(sBMZDiagnosisInfoVoResponse.getDiagnosisDoctorName());
        medicalOutpatientDiagnosis.setMedicalDiagnosisCode(sBMZDiagnosisInfoVoResponse.getMedicalDiagnosisCode());
        medicalOutpatientDiagnosis.setMedicalDiagnosisName(sBMZDiagnosisInfoVoResponse.getMedicalDiagnosisName());
        medicalOutpatientDiagnosis.setUploadTimes(0);
        medicalOutpatientDiagnosis.setUploadFlag(new Short("0"));
        medicalOutpatientDiagnosis.setCreatedTime(DateUtils.dateToString(new Date()));
        return medicalOutpatientDiagnosis;
    }


}
